package com.ch.szh.util;

import java.util.Random;

public class a {
    public static String encode(String Src){
        String Key = "CHPS.V1";
        int  KeyLen = Key.length();
        int  KeyPos = -1;
        int Range = 256;
        int SrcAsc = 0;
        Random x = new Random();
        Integer offset = x.nextInt(Range);
        System.out.println(offset);
        String dest = String.format("%02x", offset).toUpperCase();
        System.out.println(dest);

        for(int SrcPos = 0; SrcPos < Src.length(); SrcPos++)
        {
            SrcAsc = ((int)(Src.charAt(SrcPos)) + offset) % 255;

            if (KeyPos < KeyLen - 1)
                KeyPos = KeyPos + 1;
            else
                KeyPos = 0;

            SrcAsc = SrcAsc ^ (int)(Key.charAt(KeyPos));
            dest = dest + String.format("%02x", SrcAsc).toUpperCase();      //       Integer.toHexString(SrcAsc).toUpperCase();
            offset = SrcAsc;
        }
        return dest;
    }

    public static String uncode(String Src){
        String Key = "CHPS.V1";
        int  KeyLen = Key.length();
        int  KeyPos = -1;
        int Range = 256;
        int SrcAsc = 0;
        int TmpSrcAsc = 0;
        String dest = "";
        //int offset =     Integer.parseInt(Src.substring(0, 2), 16);
        int offset =     Integer.valueOf(Src.substring(0, 2), 16).intValue();
        int SrcPos = 2;
        do {
            SrcAsc =Integer.valueOf(Src.substring(SrcPos, 2 + SrcPos), 16).intValue();
            if (KeyPos < KeyLen - 1)
                KeyPos = KeyPos + 1;
            else
                KeyPos = 0;
            TmpSrcAsc = SrcAsc ^ (int)(Key.charAt(KeyPos));
            if (TmpSrcAsc <= offset)
                TmpSrcAsc = 255 + TmpSrcAsc - offset;
            else
                TmpSrcAsc = TmpSrcAsc - offset;
            dest = dest +(char)TmpSrcAsc;
            System.out.println(dest);
            offset = SrcAsc;
            SrcPos = SrcPos + 2;
        }while( SrcPos <= Src.length() - 1);
        System.out.print(dest);
        return  dest;
    }

    public static void main(String[] args){
        System.out.println(a.encode("asd123.com"));
    }
}
